<template>
  <Layout @size-change="sizeChange">
    <template #left-content>
      <!--  <el-splitter>-->
      <!--    <el-splitter-panel @update:size="sizeChange" :min="250">-->
      <div class="left-main" :style="{ width: `${searchSize}px` }" @click="showMenuCard = false">
        <!--        搜索栏 -->
        <div class="search drag" :style="{ width: `${searchSize}px` }">
          <div class="no-drag">
            <div
              v-if="leftInfoType === 0"
              :style="{ width: `${searchSize - 50}px` }"
              class="search-input-a"
              @click.stop="switchInput(1)"
            >
              <span class="iconfont icon-search"></span>&nbsp;
              <span style="font-size: 13px; user-select: none">搜索</span>
            </div>
            <div
              v-if="leftInfoType === 1"
              class="search-input-b"
              :style="{ width: `${searchSize - 50}px` }"
            >
              <el-input
                ref="inputRef"
                v-model="searchValue"
                clearable
                placeholder=""
                @input="executeSearch"
                @blur.stop="switchInput(0)"
              >
                <template #suffix>
                  <el-button
                    key="primary"
                    type="text"
                    style="width: max-content"
                    @click.stop="switchInput(0)"
                    >取消
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
        </div>
        <!--        会话列表-->
        <div class="chat-list">
          <el-scrollbar ref="chatSessionInfoListRef" class="chat-list-scrollbar">
            <div v-for="item in chatSessionInfoList" :key="item.sessionId">
              <div
                :id="'session_' + item.sessionId"
                :class="[
                  'chat-item',
                  currentSelectionSession.sessionId === item.sessionId ? 'active' : ''
                ]"
                @click.stop="sendMessage(item)"
                @contextmenu="
                  (e) => {
                    showMenu(e, item)
                  }
                "
              >
                <div class="l">
                  <div class="avatar">
                    <el-badge
                      :value="item.noReadCount"
                      class="item"
                      :is-dot="false"
                      :show-zero="false"
                    >
                      <el-avatar
                        :size="45"
                        :src="
                          Tool.getAvatar(
                            item.contactInfo.contactUserId,
                            item.contactInfo.avatar,
                            500
                          )
                        "
                        shape="square"
                      />
                    </el-badge>
                  </div>
                  <div class="chat-info">
                    <div class="top">
                      <div class="name">
                        <el-text
                          truncated
                          :style="{ width: `${searchSize - 160}px`, color: '#000' }"
                        >
                          {{
                            determineNoteNameIsEmpty(item.contactInfo.noteName)
                              ? item.contactInfo.nickName
                              : item.contactInfo.noteName
                          }}
                        </el-text>
                      </div>
                    </div>
                    <div class="bottom">
                      <div v-if="item.sessionType === 1" class="content-group">
                        <div class="content-chat-content">
                          <el-text
                            truncated
                            :style="{
                              width: `${searchSize - 160}px`,
                              color: '#7a7a7a',
                              fontSize: '12px'
                            }"
                          >
                            {{ item.lastMessage }}
                          </el-text>
                        </div>
                      </div>
                      <div v-if="item.sessionType === 2" class="content-chat">
                        <div class="content-chat-content">群聊消息</div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="time">
                  <div class="time-text">{{ getTime(item) }}</div>
                  <div class="iconfont icon-qingwudarao"></div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </template>
    <template #right-content>
      <!--    </el-splitter-panel>-->
      <!--    <el-splitter-panel :min="460">-->
      <div
        class="right-main"
        @dragenter="handleDragEnter"
        @dragover="handleDragOver"
        @dragleave="handleDragLeave"
        @drop="handleDrop"
        @dragstart="handleDragStart"
        @click="showMenuCard = false"
      >
        <div v-if="showBlankPage">
          <div class="blank-page-top drag"></div>
          <div class="iconfont icon-chat blank-page"></div>
        </div>
        <div v-if="!showBlankPage" class="head drag">
          <div v-if="currentSelectionSession.contactInfo">
            {{
              determineNoteNameIsEmpty(currentSelectionSession.contactInfo.noteName)
                ? currentSelectionSession.contactInfo.nickName
                : currentSelectionSession.contactInfo.noteName
            }}
          </div>
          <div class="more no-drag" title="更多聊天信息" @click.stop="switchIsShowDrawer">
            <span class="iconfont icon-more"></span>
          </div>
        </div>
        <div v-if="!showBlankPage" class="chat-list" :style="{ width: `${rightChatListSize}px` }">
          <!--          <el-scrollbar ref="chatMessageListRef" class="chat-list-scrollbar">-->
          <!--            <div v-for="item in currentSelectionMessageList" :key="item.messageId">-->
          <!--              <div :id="`msg${item.messageId}`">{{ item }}</div>-->
          <!--            </div>-->
          <!--          </el-scrollbar>-->

          <el-scrollbar ref="chatMessageListRef" class="chat-list-scrollbar">
            <div
              v-for="item in currentSelectionMessageList"
              :id="`msg${item.messageId}`"
              :key="item.messageId"
              class="message-wrapper"
              :class="{
                'mine-wrapper': item.sendUserId === userInfo.userId,
                'other-wrapper': item.sendUserId !== userInfo.userId
              }"
            >
              <div
                v-if="item.type"
                class="time-module"
                :style="{ width: `${rightChatListSize}px` }"
              >
                <div>
                  {{ item.time }}
                </div>
              </div>

              <div v-if="!item.type && item.sendUserId">
                <!-- 对方消息：头像 + 消息 -->
                <div v-if="item.sendUserId !== userInfo.userId" class="message-group other-group">
                  <el-avatar
                    :size="40"
                    :src="
                      Tool.getAvatar(
                        currentSelectionSession.contactInfo.contactUserId,
                        currentSelectionSession.contactInfo.avatar,
                        500
                      )
                    "
                    shape="square"
                    class="message-avatar"
                  />
                  <div
                    v-if="item.messageType === 201"
                    :id="`msg${item.messageId}`"
                    class="message-image"
                  >
                    <template v-if="item.messageType === 201">
                      <!-- 图片消息 -->
                      <img
                        :src="
                          `http://localhost:${getExpressPort()}/image?filename=` +
                          item.fileName +
                          '&sessionId=' +
                          item.sessionId
                        "
                        alt="图片消息"
                        class="media-content"
                      />
                    </template>
                  </div>
                  <div
                    v-if="item.messageType === 2"
                    :id="`msg${item.messageId}`"
                    :class="['bubble', 'other']"
                  >
                    <template v-if="item.messageType === 2">
                      <!-- 文本消息 -->
                      {{ item.messageContent }}
                    </template>
                  </div>
                </div>

                <!-- 自己的消息：消息 + 头像 -->
                <div v-else class="message-group mine-group">
                  <div
                    v-if="item.sendStatus === 3 || item.sendStatus === 5"
                    class="message-warning"
                    title="点击重新发送"
                    @click="reSend(item)"
                  >
                    <div>!</div>
                  </div>
                  <div>
                    <div
                      v-if="item.messageType === 201"
                      :id="`msg${item.messageId}`"
                      class="message-image"
                    >
                      <template v-if="item.messageType === 201">
                        <!-- 图片消息 -->
                        <img
                          :src="
                            `http://localhost:${getExpressPort()}/image?filename=` +
                            item.fileName +
                            '&sessionId=' +
                            item.sessionId
                          "
                          alt="图片消息"
                          class="media-content"
                        />
                      </template>
                    </div>
                    <div
                      v-if="item.messageType === 202"
                      :id="`msg${item.messageId}`"
                      class="message-video"
                    >
                      <template v-if="item.messageType === 202">
                        <!-- 视频消息 -->
                        <video
                          :src="
                            `http://localhost:${expressPort}/video?filename=` +
                            item.fileName +
                            '&sessionId=' +
                            item.sessionId
                          "
                          controls
                          class="media-content"
                        ></video>
                      </template>
                    </div>

                    <div
                      v-if="item.messageType === 2"
                      :id="`msg${item.messageId}`"
                      :class="['bubble', 'mine']"
                    >
                      <template v-if="item.messageType === 2">
                        <!-- 文本消息 -->
                        {{ item.messageContent }}
                      </template>
                    </div>
                    <div style="color: #7a7a7a; font-size: 12px; margin-top: 2px">
                      <span v-if="item.sendStatus === 3"
                        >对方还不是你的朋友请先添加好友在发送消息</span
                      >
                      <span v-if="item.sendStatus === 5">对方拒绝接受你的消息</span>
                      <div
                        v-if="item.sendStatus === 3"
                        style="color: #2cb6fe; cursor: pointer"
                        @click="addFriend()"
                      >
                        点击添加好友
                      </div>
                      <div
                        v-if="item.sendStatus === 5"
                        style="color: #2cb6fe; cursor: pointer"
                        @click="reSend(item)"
                      >
                        点击重新发送
                      </div>
                    </div>
                  </div>
                  <el-avatar
                    :size="40"
                    :src="Tool.getAvatar(userInfo.userId, userInfo.avatar, 500)"
                    shape="square"
                    class="message-avatar"
                  />
                </div>
              </div>
            </div>
          </el-scrollbar>

          <div class="chat-input">
            <div class="headA">
              <div>
                <span class="headA-a iconfont icon-emoji-happy" title="表情"></span>&nbsp;
                <span class="headA-a iconfont icon-folder" title="发送文件"></span>&nbsp;
                <span class="headA-a iconfont icon-message" title="聊天记录"></span>
                <el-badge
                  :value="messageFile.length"
                  :is-dot="false"
                  :show-zero="false"
                  @click="switchAnnexCard"
                >
                  <span
                    class="headA-a iconfont icon-fujian"
                    title="添加附件"
                    style="color: #000; padding-left: 10px"
                  >
                  </span>
                </el-badge>
              </div>
              <div v-if="showAnnexCard" class="annex" @click.self="Tool.playWarningTone()">
                <el-card class="annex-card">
                  <div class="title">
                    <div>发送附件</div>
                  </div>
                  <el-scrollbar style="height: 300px">
                    <div v-for="(item, index) in messageFile" :key="index" class="annex-item">
                      <div class="annex-item-content">
                        <div class="file-icon">
                          <img :src="getImgUrl(item.type)" alt="" width="50" />
                        </div>
                        <div class="file-info">
                          <div class="file-name">
                            <el-popover
                              placement="top-start"
                              :width="150"
                              trigger="hover"
                              :content="item.name"
                              popper-style="color:#000;width: max-content;border: 1px solid #eae7e6;"
                            >
                              <template #reference>
                                <el-text truncated style="width: 180px">
                                  {{ item.name }}
                                </el-text>
                              </template>
                            </el-popover>
                          </div>
                          <div class="file-size">{{ Tool.calculateSize(item.size) }}</div>
                        </div>
                        <div class="file-delete" title="删除">
                          <span
                            class="iconfont icon-lajitong"
                            @click.stop="deleteSendMessageFile(item)"
                          ></span>
                        </div>
                      </div>
                    </div>
                  </el-scrollbar>
                  <div class="annex-bottom">
                    <div>
                      <el-upload
                        action="#"
                        :http-request="
                          (e) => {
                            requestUpload(e)
                          }
                        "
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                      >
                        <el-button class="el-button-left" type="primary">添加</el-button>
                      </el-upload>
                    </div>
                    <div>
                      <el-button
                        class="el-button-right"
                        type="primary"
                        @click.stop="switchAnnexCard"
                        >关闭
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
              <div>
                <span class="iconfont icon-phone" title="语音聊天"></span>&nbsp;
                <span class="iconfont icon-shexiangtou" title="视频聊天"></span>&nbsp;
              </div>
            </div>
            <div class="input-content">
              <div
                id="message-input"
                ref="msgInput"
                contenteditable="true"
                spellcheck="false"
                :style="{ width: vw - 310 + 'px' }"
                @input="
                  (e) => {
                    inputSendMessage(e)
                  }
                "
                @keydown.enter="(e) => sendA(e)"
                @paste="
                  (e) => {
                    handlePaste(e)
                  }
                "
              ></div>
            </div>
            <div class="send-button">
              <el-button
                v-if="messageContent.length === 0 && messageFile.length === 0"
                class="disabled-button"
                type="primary"
                >发送
              </el-button>
              <el-button
                v-if="messageContent.length > 0 || messageFile.length > 0"
                class="not-disabled-button"
                type="primary"
                @click.stop="sendB"
                >发送
              </el-button>
            </div>
          </div>
        </div>

        <el-drawer v-model="isShowDrawer" :with-header="false">
          <div class="drawer">测试00000000</div>
        </el-drawer>
        <div
          v-if="isShowMask"
          class="Drag-the-mask"
          :style="{ width: vw - 310 + 'px', height: vh + 'px' }"
        ></div>
      </div>
      <!--    </el-splitter-panel>-->
      <!--  </el-splitter>-->
    </template>
  </Layout>

  <div v-if="showMenuCard" class="menu-card" :style="[{ left: x + 'px', top: y + 'px' }]">
    <el-card class="card">
      <div class="card-text" @click.stop="">置顶</div>
      <div class="card-text" @click.stop="">取消置顶</div>
      <div class="card-text" @click.stop="">消息免打扰</div>
      <div class="card-text delete-contact" @click.stop="deleteSessionA">删除</div>
    </el-card>
  </div>
  <div v-if="showDeleteContactCard" class="card-contact" @click.self="Tool.playWarningTone()">
    <el-card class="card-contact-info">
      <div style="padding: 20px">
        <div>
          是否确认删除该会话？<span style="color: red"><br />删除会话将会删除所有聊天记录</span>
        </div>
        <div class="button">
          <el-button @click.stop="showDeleteContactCard = false">取消</el-button>
          <el-button type="primary" @click.stop="deleteSession">确定</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import Layout from '#/components/Layout.vue'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import Tool from '#/utils/Tool'
import { useContactInfoStore } from '#/stores/ContactInfoStore'
import { useUserInfoStore } from '#/stores/UserInfoStore'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import Api from '../../utils/Api'
import moment from 'moment'
import 'moment/dist/locale/zh-cn' // 引入中文语言包
moment.locale('zh-cn') // 设置语言为中文

const userInfoStore = useUserInfoStore() // 登录用户信息
const contactInfoStore = useContactInfoStore() // 存储联系人信息  用户的所有联系人
const route = useRoute()

const inputRef = ref() // 搜索输入框的引用
const chatSessionInfoListRef = ref() // 聊天会话div引用
const chatMessageListRef = ref() // 聊天会话div引用

const leftInfoType = ref(0) // 0 聊天列表 1搜索结果
const searchValue = ref('') // 搜索内容
const isShowDrawer = ref(false) // 是否显示抽屉
const isShowMask = ref(false) // 是否显示遮罩

const showBlankPage = ref(true) // 显示空白页
const messageContent = ref('') // 发送的消息内容
const msgInput = ref() // 消息输入框的引用
const messageFile = ref([]) // 发送的消息内容
const showAnnexCard = ref(false) // 是否显示附件卡片

const x = ref() // 右键x坐标
const y = ref() // 右键y坐标
const showMenuCard = ref(false) // 是否显示菜单  右键点击
const showDeleteContactCard = ref(false) // 是否显示删除联系人提示卡片
const needDeleteSessionId = ref(null)
// 所有联系人列表
const contactList = computed(() => {
  return contactInfoStore.getContactInfoList()
})
// 聊天会话列表
const chatSessionInfoList = ref([])

const session = {
  sessionId: -1,
  sessionType: 1,
  userId: -1,
  contactId: -1,
  contactList: [],
  lastMessage: '',
  lastReceiveTime: 0,
  noReadCount: 0,
  topType: 0,
  status: 1
}

// 会话 选择的会话信息
const currentSelectionSession = ref(session)

// 聊天消息 列表 选择的聊天会话消息列表
const currentSelectionMessageList = ref()

// 登录用户信息
const userInfo = computed(() => {
  return userInfoStore.getUserInfo()
})

const vh = ref(window.innerHeight) // 获取窗口高度
// const vh = ref(document.documentElement.clientHeight);
const vw = ref(window.innerWidth) // 获取窗口宽度
// 监听窗口变化
window.addEventListener('resize', () => {
  vh.value = window.innerHeight // 获取窗口高度
  vw.value = window.innerWidth // 获取窗口宽度
})

/**
 * 执行搜索
 */
const executeSearch = () => {}

let num = 0

const handleDragEnter = (e) => {
  e.preventDefault()
  // 拖拽进入时触发，更新拖拽状态，比如改变背景颜色
  console.log('handleDragEnter')
  if (num === 0) {
    isShowMask.value = true
  }
  num += 1
}

const handleDragOver = (e) => {
  e.preventDefault()
  // 必须阻止默认行为以激活拖放区域（调用e.preventDefault()），比如改变背景颜色
  console.log('handleDragOver')
}

const handleDragLeave = (e) => {
  e.preventDefault()
  // 拖拽离开时重置状态，比如恢复背景颜色
  console.log('handleDragLeave')
  num -= 1
  if (num === 0) {
    isShowMask.value = false
  }
}

const handleDrop = (e) => {
  e.preventDefault()
  isShowMask.value = false
  // 释放文件时处理数据
  const files = e.dataTransfer.files
  // 处理文件，比如上传文件或显示文件信息
  for (const file of files) {
    console.log(file)
    // 你可以在这里调用上传文件的函数
    messageFile.value.push(file)
  }
  showAnnexCard.value = true
}

/**
 * 切换输入框
 * @param val
 */
const switchInput = (val) => {
  leftInfoType.value = val
  if (val === 1) {
    nextTick(() => {
      inputRef.value.focus() // 使搜索输入框获取焦点
    })
  }
}
const switchIsShowDrawer = () => {
  isShowDrawer.value = !isShowDrawer.value
}

const getUser = (id) => {
  let obj = {}
  for (let i = 0; i < contactList.value.length; i++) {
    let item = contactList.value[i]
    let bol = false
    for (let j = 0; j < item.value.length; j++) {
      let item2 = item.value[j]
      if (item2.contactUserId === id) {
        obj = item2
        bol = true
        break
      }
    }
    if (bol) {
      break
    }
  }
  return obj
}

/**
 * 选中会话发送消息
 * @param item
 * @param loadMessage 是否需要加载所有的消息
 */
// const sendMessage123 = async (item, loadMessage = true) => {
//   if (item.sessionId === currentSelectionSession.value.sessionId) {
//     currentSelectionSession.value = session
//     showBlankPage.value = true
//     messageContent.value = ''
//     messageFile.value = []
//     return
//   }
//   item.noReadCount = 0
//   currentSelectionSession.value = item // 设置当前选中的会话
//   // 获取 聊天会话列表
//   let list = loadMessage
//     ? await window.ipcRenderer.invoke('getAllMessageBySessionId', item.sessionId)
//     : []
//
//   const processedList = []
//   for (let i = 0; i < list.length; i++) {
//     let aTime = list[i].sendTime
//     let cTime = list[i + 1] ? list[i + 1].sendTime : 0
//     let bTime = Date.now()
//     let time = bTime - aTime
//     if (cTime - aTime > 2 * 60 * 1000 || i === 0) {
//       // 如果小于一天
//       if (time < 24 * 60 * 60 * 1000) {
//         processedList.push({
//           type: 'time',
//           time: moment(aTime).format('HH:mm')
//         })
//         // 大于一天 小于两天
//       } else if (24 * 60 * 60 * 1000 < time < 2 * 24 * 60 * 60 * 1000) {
//         processedList.push({
//           type: 'time',
//           time: '昨天 ' + moment(aTime).format('HH:mm')
//         })
//         // 大于两天 小于 7天
//       } else if (time > 2 * 24 * 60 * 60 * 1000) {
//         processedList.push({
//           type: 'time',
//           time: moment(aTime).format('dddd HH:mm')
//         })
//         // 大于七天
//       } else {
//         processedList.push({
//           type: 'time',
//           time: moment(aTime).format('YYYY-MM-DD')
//         })
//       }
//     }
//     processedList.push(list[i])
//   }
//   console.log(processedList)
//   currentSelectionMessageList.value = processedList
//   showBlankPage.value = false
//   messageContent.value = ''
// }
/**
 * 选中会话发送消息
 * @param item
 * @param loadMessage 是否需要加载所有的消息
 */
const sendMessage = async (item, loadMessage = true) => {
  if (item.sessionId === currentSelectionSession.value.sessionId) {
    currentSelectionSession.value = session
    showBlankPage.value = true
    messageContent.value = ''
    messageFile.value = []
    return
  }
  item.noReadCount = 0
  currentSelectionSession.value = item // 设置当前选中的会话
  // 获取 聊天会话列表
  let list = loadMessage
    ? await window.ipcRenderer.invoke('getAllMessageBySessionId', item.sessionId)
    : []

  const processedList = []
  for (let i = 0; i < list.length; i++) {
    // 对于第一条消息或者与前一条消息间隔超过2分钟的情况，添加时间标记
    if (i === 0 || list[i].sendTime - list[i - 1].sendTime > 2 * 60 * 1000) {
      const messageTime = list[i].sendTime
      const currentTime = Date.now()
      const timeDiff = currentTime - messageTime

      // 根据时间差决定显示什么格式的时间
      if (timeDiff < 24 * 60 * 60 * 1000) {
        // 24小时内，只显示时间
        processedList.push({
          type: 'time',
          time: moment(messageTime).format('HH:mm')
        })
      } else if (timeDiff < 2 * 24 * 60 * 60 * 1000) {
        // 昨天的消息
        processedList.push({
          type: 'time',
          time: '昨天 ' + moment(messageTime).format('HH:mm')
        })
      } else if (timeDiff < 7 * 24 * 60 * 60 * 1000) {
        // 一周内，显示星期几+时间
        processedList.push({
          type: 'time',
          time: moment(messageTime).format('dddd HH:mm')
        })
      } else {
        // 超过一周，显示完整日期
        processedList.push({
          type: 'time',
          time: moment(messageTime).format('YYYY-MM-DD')
        })
      }
    }

    // 添加实际消息
    processedList.push(list[i])
  }

  currentSelectionMessageList.value = processedList
  showBlankPage.value = false
  messageContent.value = ''
  await nextTick(() => {
    let targetElement = document.getElementById(
      'msg' + processedList[processedList.length - 1]?.messageId
    )
    chatMessageListRef.value.wrapRef.scrollTop = targetElement?.offsetTop
  })
}

/**
 * 选中会话发送消息
 * @param sessionId  联系人的用户id
 */
const sendMessageB = async (sessionId) => {
  // 查看会话是否存在
  let curSession = chatSessionInfoList.value.some((item) => {
    return item.sessionId === sessionId
  })
  // 不存在创建新的
  if (!curSession) {
    // 还没有该会话
    // 创建新的会话
    let session = {
      sessionId: sessionId,
      sessionType: 1,
      userId: userInfo.value.userId,
      contactId: sessionId,
      contactList: null,
      lastMessage: null,
      lastReceiveTime: null,
      noReadCount: 0,
      topType: 0,
      status: 1
    }
    const res = await window.ipcRenderer.invoke('addChatSession', session)
    if (res.status) {
      session.contactInfo = getUser(session.contactId) // 根据联系人id获取联系人的信息
      chatSessionInfoList.value.unshift(session) // 添加到会话到会话列表在列表的第一个
      await sendMessage(session, false) // 发送消息
      return false
    } else {
      console.error('创建新的会话失败:', res.msg)
      ElMessage.error('创建新的会话失败:', res.msg)
    }
  } else {
    // 存在会话
    await sendMessage(curSession)
    return true
  }
}
const inputSendMessage = (e) => {
  messageContent.value = e.target.innerText
}
/*
 * 处理粘贴事件  输入框粘贴文件,文本 处理
 * @param e 粘贴事件
 *
 */
const handlePaste = (e) => {
  e.preventDefault() // 阻止默认粘贴事件
  const items = e.clipboardData.items // 获取粘贴的内容
  for (const item of items) {
    if (item.kind === 'string' && item.type === 'text/plain') {
      // 处理纯文本
      item.getAsString((text) => {
        document.getElementById('message-input').innerText = messageContent.value + text
        messageContent.value += text
        moveCursorEnd() // 将光标移至末尾
      })
      // // 处理纯文本
      // const text = (e.clipboardData || window.clipboardData).getData('text/plain') // 获取纯文本
      // document.getElementById('message-input').innerText = messageContent.value + text
      // messageContent.value += text
      // moveCursorEnd() // 将光标移至末尾
    } else if (item.kind === 'file' && item.type !== '') {
      // 处理文件
      const file = item.getAsFile()
      // 判断文件是否超过1gb
      if (file.size > 1024 * 1024 * 1024) {
        ElMessage.error('文件大小超过1GB')
        return
      }
      messageFile.value.push(file)
      moveCursorEnd() // 将光标移至末尾
    } else if (item.type === '') {
      ElMessage.error('不支持该文件类型')
    }
  }
}

const moveCursorEnd = () => {
  // 获取当前编辑区域的内容

  // const range = document.createRange()
  const selection = window.getSelection()
  const range = selection.getRangeAt(0)

  // 将光标移到最后
  range.selectNodeContents(msgInput.value)
  range.collapse(false) // 将光标移到末尾
  selection.removeAllRanges() // 清除所有选择范围
  selection.addRange(range) // 添加新的选择范围
}

/**
 * 发送消息 按 enter 键 发送消息
 */
const sendA = (e) => {
  e.preventDefault() // 阻止默认的换行行为
  if (e.key === 'Enter') {
    sendB()
  }
}
/**
 * 发送消息  点击按钮发送
 */
const sendB = () => {
  if (messageContent.value !== '' || messageFile.value.length > 0) {
    sendTextMessage()
    sendFileMessage()
    messageContent.value = ''
    messageFile.value = []
    document.getElementById('message-input').innerText = ''
  }
}
/**
 * 发送文本消息
 * @returns {Promise<void>}
 */
const sendTextMessage = async () => {
  // 发送文本消息
  if (messageContent.value === '') {
    return
  }

  // todo 判断好友关系情况  如果是被拉黑 或者被好友删除，添加本地消息  不向服务器发送保存消息
  console.log('发送文本消息', messageContent.value)
  let message = {
    messageId: Tool.generateUUID(), // 消息id
    messageType: 2, // 消息类型 2 文本消息
    messageCode: 1, // 消息码 1 用户 2 群聊
    messageContent: messageContent.value, // 消息内容
    sessionId: currentSelectionSession.value.contactId, // 会话id
    sendUserId: userInfo.value.userId, // 发送用户id
    contactId: currentSelectionSession.value.contactId, // 接收用户id
    groupId: currentSelectionSession.value.contactId, // 接收用户id
    sendTime: new Date().getTime(), // 发送时间
    sendStatus: 1 // 发送状态 0 发送中  1 发送成功
  }
  const res = await Api.sendMessage(message)
  if (res.code === 200) {
    res.data.sendStatus = 1
    // 本地保存 文本 消息
    await localSavaMessage(res.data)
  } else if (res.code === 901) {
    //你还不是对方的好友
    message.sendStatus = 3
    await localSavaMessage(message)
  } else if (res.code === 902) {
    //对方拒绝接收你的消息
    message.sendStatus = 5
    await localSavaMessage(message)
  }
}
const sendFileMessage = async () => {
  if (messageFile.value.length === 0) {
    return
  }

  //文本消息 2
  //图片  201
  //视频  202
  //文件  203
  //语音  204
  //未知  205

  console.log('发送文件消息', messageFile.value)

  for (let i = 0; i < messageFile.value.length; i++) {
    let file = messageFile.value[i]
    const filePath = file.path
    const fileType = getType(file.type)

    let message = {
      messageId: null, // 消息id
      messageType: fileType, // 消息类型 2 文本消息
      messageCode: 1, // 消息码 1 用户 2 群聊
      messageContent: file.name, // 消息内容
      sessionId: currentSelectionSession.value.contactId, // 会话id
      sendUserId: userInfo.value.userId, // 发送用户id
      contactId: currentSelectionSession.value.contactId, // 接收用户id
      groupId: currentSelectionSession.value.contactId, // 接收用户id
      sendTime: new Date().getTime(), // 发送时间
      sendStatus: 0, // 发送状态 0 发送中  1 发送成功
      fileName: file.name,
      fileSize: file.size,
      fileType: fileType
    }
    let formData = new FormData() // 请求表单
    formData.append('messageType', fileType)
    formData.append('userId', currentSelectionSession.value.contactId)
    formData.append('file', file)

    const r = await Api.sendFileMessage(formData)
    if (r.code !== 200) {
      ElMessage.error(r.msg)
      return
    }
    const res = await Api.sendMessage(message)
    if (res.code !== 200) {
      ElMessage.error(r.msg)
      return
    }
    message.messageId = Tool.generateUUID()
    if (res.code === 901) {
      //对方还不是你的好友
      message.sendStatus = 4
    }
    if (res.code === 902) {
      //对方拒绝接收你的消息
      message.sendStatus = 3
    }

    localSavaMessage(message, 11, {
      type: fileType,
      filePath: filePath,
      fileName: file.name,
      sessionId: currentSelectionSession.value.contactId
    })
  }
}

const reSend = async (message) => {
  const res = await Api.sendMessage(message)
  if (res.code === 200) {
    res.data.sendStatus = 1
    // 本地保存 文本 消息
    await localSavaMessage(res.data)
  } else if (res.code === 901) {
    //你还不是对方的好友
    message.sendStatus = 3
    await localSavaMessage(message)
  } else if (res.code === 902) {
    //对方拒绝接收你的消息
    message.sendStatus = 5
    await localSavaMessage(message)
  }
}
const addFriend = async () => {
  const contactInfo = { ...currentSelectionSession.value.contactInfo }
  console.log('添加好友', contactInfo)
  const addFriendApplyFormData = {
    userId: userInfo.value.userId, // 登录用户 用户id
    contactUserId: contactInfo.contactUserSweetCircleId, // 添加的联系人userId
    userSweetCircleId: contactInfo.contactUserSweetCircleId, // 添加的联系人甜甜圈id
    noteName: contactInfo.noteName, // 备注名
    applyMsg: `我是${userInfo.value.nickName}`, // 申请消息
    sweetCircleAuth: contactInfo.sweetCircleAuth, // 甜甜圈状态
    sweetCircleStatusA: contactInfo.sweetCircleStatusA, // 甜甜圈状态
    sweetCircleStatusB: contactInfo.sweetCircleStatusB // 甜甜圈状态
  }
  const response = await Api.addContact(addFriendApplyFormData)
  if (response.code === 200) {
    ElMessage.success('好友申请消息已发送')
  }
}

const localSavaMessage = async (message, code, file) => {
  const addChatMessageResult = await window.ipcRenderer.invoke(
    'addChatMessage',
    message,
    code,
    file
  )
  if (!addChatMessageResult.status) {
    ElMessage.error(addChatMessageResult.msg)
    return
  }
  if (addChatMessageResult.data) {
    message.messageContent = addChatMessageResult.data.filePath
  }
  // 判断是不是选择的会话
  if (message.sessionId === currentSelectionSession.value.sessionId) {
    // 检查是否需要添加时间标记
    const lastItem = currentSelectionMessageList.value[currentSelectionMessageList.value.length - 1]

    // 如果最后一条消息不是时间消息，且与新消息间隔超过2分钟，则添加时间消息
    if (!lastItem || !lastItem.type) {
      const lastMessageTime = lastItem ? lastItem.sendTime : 0
      if (message.sendTime - lastMessageTime > 2 * 60 * 1000) {
        currentSelectionMessageList.value.push({
          type: 'time',
          time: moment(message.sendTime).format('HH:mm')
        })
      }
    }
    currentSelectionMessageList.value.push(message)
  } else {
    // 不是选中的会话
    // 判断 存在该会话
    if (
      chatSessionInfoList.value.some((sessionInfo) => sessionInfo.sessionId === message.sessionId)
    ) {
      chatSessionInfoList.value.forEach((sessionInfo) => {
        if (sessionInfo.sessionId === message.sessionId) {
          sessionInfo.lastMessage = message.messageContent
          sessionInfo.noReadCount += 1
          sessionInfo.lastReceiveTime = message.sendTime
        }
      })
      // 不存在该会话
    } else {
      // 创建新的会话
      let session
      if (message.messageCode === 1) {
        // 私聊
        session = {
          sessionId: message.sessionId,
          sessionType: message.messageCode,
          userId: userInfo.value.userId,
          contactId: message.sendUserId,
          contactList: null,
          lastMessage: message.messageContent,
          lastReceiveTime: message.sendTime,
          noReadCount: 1,
          topType: 0,
          status: 1
        }
        // 保存会话
        const res = await window.ipcRenderer.invoke('addChatSession', session)
        if (res.status) {
          session.contactInfo = getUser(session.contactId) // 根据联系人id获取联系人的信息
          chatSessionInfoList.value.unshift(session) // 添加到会话到会话列表在列表的第一个
        } else {
          ElMessage.error('创建新的会话失败:', res.msg)
        }
      } else {
        // 群聊
        session = {
          sessionId: message.sessionId,
          sessionType: message.messageCode,
          userId: userInfo.value.userId,
          contactId: message.sendUserId,
          contactList: null,
          lastMessage: null,
          lastReceiveTime: null,
          noReadCount: 0,
          topType: 0,
          status: 1
        }
      }
    }
  }
  let msg = ''
  if (message.messageType === 2) {
    msg = message.messageContent
  } else if (message.messageType === 201) {
    msg = '[图片]'
  } else if (message.messageType === 203) {
    msg = '[视频]'
  }
  currentSelectionSession.value.lastMessage = msg
  currentSelectionSession.value.lastReceiveTime = message.sendTime

  await nextTick(() => {
    let targetElement = document.getElementById('msg' + message.messageId)
    chatMessageListRef.value.wrapRef.scrollTop = targetElement.offsetTop
  })
}

const getType = (type) => {
  //图片  201
  //视频  202
  //文件  203
  //语音  204
  //位置  206
  //未知  205

  if (type.indexOf('image') !== -1) {
    return 201
  } else if (type.indexOf('audio') !== -1) {
    return 204
  } else if (type.indexOf('video') !== -1) {
    return 202
  } else if (type === '') {
    return 205 //
  } else {
    return 203
  }
}

const determineNoteNameIsEmpty = (notName) => {
  if (notName === '' || notName === null || notName === undefined) {
    return true
  }
}

const switchAnnexCard = () => {
  showAnnexCard.value = !showAnnexCard.value
}

const deleteSendMessageFile = (item) => {
  messageFile.value.splice(messageFile.value.indexOf(item), 1)
}
// const getFileNameSuffix = (name) => {
//   let fileName2 = name.split('.')
//   return (
//     fileName2[0].substring(fileName2[0].length - 1, fileName2[0].length) +
//     '.' +
//     fileName2[fileName2.length - 1]
//   )
// }

const getImgUrl = (type) => {
  if (
    type === 'text/csv' ||
    type === 'application/vnd.ms-excel' ||
    type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ) {
    return Tool.baseUrl + '/static/file/csv.png'
  } else if (type === 'application/x-zip-compressed') {
    return Tool.baseUrl + '/static/file/zip.png'
  } else if (type === 'application/x-msdownload') {
    return Tool.baseUrl + '/static/file/exe.png'
  } else if (type.indexOf('audio') !== -1) {
    return Tool.baseUrl + '/static/file/music.png'
  } else if (type.indexOf('video') !== -1) {
    return Tool.baseUrl + '/static/file/video.png'
  } else if (type === 'application/pdf') {
    return Tool.baseUrl + '/static/file/pdf.png'
  } else if (
    type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||
    type === 'application/vnd.ms-powerpoint'
  ) {
    return Tool.baseUrl + '/static/file/ppt.png'
  } else if (
    type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
    type === 'application/msword'
  ) {
    return Tool.baseUrl + '/static/file/word.png'
  } else if (type === 'text/plain') {
    return Tool.baseUrl + '/static/file/txt.png'
  } else {
    return Tool.baseUrl + '/static/file/unknown.png'
  }
}

const handleDragStart = (e) => {
  e.preventDefault() // 阻止默认的拖拽行为
}

/**
 * 覆盖默认的拖拽上传事件
 */
const requestUpload = () => {
  // console.log('文件上传 requestUpload', e)
}
const beforeUpload = (file) => {
  // 判断文件是否超过1gb
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.error('文件大小超过1GB')
    return
  }
  messageFile.value.push(file)

  // if (file.type.indexOf("image/") == -1) {
  //   ElMessage.error("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
  // } else {
  //   const reader = new FileReader();
  //   reader.readAsDataURL(file);
  //   reader.onload = () => {
  //     options.value.img = reader.result;
  //     options.value.filename = file.name;
  //   };
  // }
}
const searchSize = ref(260)
const rightChatListSize = computed(() => {
  return vw.value - searchSize.value - 62
})
const sizeChange = (num) => {
  searchSize.value = num
  if (showAnnexCard.value) {
    showMenuCard.value = false
  }
}
/**
 * 加载会话列表的用户信息
 * @param data  会话列表
 */
const loadChatSession = (data) => {
  chatSessionInfoList.value = data
  currentSelectionSession.value = {}
  currentSelectionMessageList.value = []
  showBlankPage.value = true

  if (data.length < 1) {
    return
  }
  data.forEach((item, index) => {
    if (item.sessionType === 1) {
      item.contactInfo = getUser(item.contactId)
      data[index] = item
    }
  })
}

const showMenu = (e, chatSession) => {
  needDeleteSessionId.value = chatSession.sessionId
  showMenuCard.value = true
  x.value = e.clientX // 设置删除卡片的 x 坐标
  y.value = e.clientY > vh.value - 75 ? e.clientY - 75 : e.clientY
}

const deleteSessionA = async () => {
  showDeleteContactCard.value = true
  showMenuCard.value = false
}
const deleteSession = async () => {
  // 删除所有的消息 包括 文本消息  文件消息

  const localMessage = await window.ipcRenderer.invoke(
    'getAllMessageBySessionId',
    needDeleteSessionId.value
  )
  if (localMessage.length > 0) {
    const res = await Api.deleteMessage(needDeleteSessionId.value) // 删除服务器的所有的保存的消息
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
  }

  const res2 = await window.ipcRenderer.invoke('deleteChatSession', needDeleteSessionId.value)
  if (res2.status) {
    // 删除chatSessionList中的会话
    chatSessionInfoList.value = chatSessionInfoList.value.filter(
      (item) => item.sessionId !== needDeleteSessionId.value
    )
    if (currentSelectionSession.value.sessionId === needDeleteSessionId.value) {
      currentSelectionSession.value = {}
      currentSelectionMessageList.value = []
      showBlankPage.value = true
    }
  } else {
    ElMessage.error(res2.msg)
  }
  showDeleteContactCard.value = false
}

const getTime = (item) => {
  let time = item.lastReceiveTime
  if (!time) {
    time = item.contactInfo.addTime
    return moment(time).format('YYYY-MM-DD')
  }

  // 将时间戳转换为 HH:MM 格式
  return moment(time).format('HH:mm')
}
const getExpressPort = () => {
  return localStorage.getItem('expressPort')
}

onMounted(async () => {
  // 加载会话
  try {
    const data = await window.ipcRenderer.invoke('getAllChatSession')
    if (!data.status) {
      ElMessage.error(data.msg)
    }
    loadChatSession(data.data)
  } catch (e) {
    console.error('加载会话列表失败', e)
  }

  // 加载会话回调
  window.ipcRenderer.on('receiveMessages', async (_, message) => {
    //图片  201
    //视频  202
    //文件  203
    //语音  204
    //位置  206
    //未知  205
    Tool.playMessage()
    if (message.messageType === 201) {
      console.log('接收到图片消息', message)
      // 保存本地文件消息
      const res = await window.ipcRenderer.invoke('saveFileMessage', {
        fileName: message.fileName,
        messageType: message.messageType,
        userId: userInfo.value.userId,
        sendUserId: message.sendUserId,
        token: localStorage.getItem('token')
      })
      console.log('保存文件消息', res)
    }
    message.sessionId = message.sendUserId
    localSavaMessage(message)
  })

  window.ipcRenderer.on('reloadSession', async (_, data) => {
    if (!data.status) {
      ElMessage.error(data.msg)
    }
    loadChatSession(data.data)
  })
})

watch(
  () => route.path, // 路由变化时
  (newVal) => {
    // console.log('路由变化', newVal, oldVal)

    if (newVal === '/chat') {
      // 如果路由等于 /chat
      if (route.query.timestamp && route.query.sessionId) {
        // 如果路由有参数 timestamp 和 sessionId  发送消息
        let res = sendMessageB(route.query.sessionId)
        if (res) {
          // 存在该会话
          const element = document.getElementById('session_' + route.query.sessionId)
          if (element && chatSessionInfoListRef.value) {
            const container = chatSessionInfoListRef.value.wrapRef
            container.scrollTop = element.offsetTop
          }
        }
      } else {
        // 如果路由没有参数  表示切换菜单
        if (currentSelectionMessageList.value && currentSelectionMessageList.value.length > 0) {
          const id = currentSelectionMessageList.value[currentSelectionMessageList.value.length - 1]
          const element = document.getElementById('msg' + id.messageId)
          if (element && chatMessageListRef.value) {
            const container = chatMessageListRef.value.wrapRef
            container.scrollTop = element.offsetTop
          }
        }
      }
    }
  }
)
</script>
<style lang="scss" scoped>
.left-main {
  height: 100vh;

  .search {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    background-color: #fff;
    border-right: 1px solid #eae7e6;
    border-bottom: 1px solid #eae7e6;

    .search-input-a {
      background: #e0e0e0;
      height: 25px;
      display: flex;
      align-items: center;
      justify-content: start;
      padding-left: 10px;
      cursor: text;
      border-radius: 5px;
    }

    .search-input-b {
      .el-input {
        height: 25px;
      }

      :deep(.el-input__wrapper) {
        height: 25px;
        box-shadow: none;
        border: 1px solid #d0d0d0;
      }
    }
  }

  .chat-list {
    user-select: none;
    background-color: #e6e6e6;
    border-right: 2px solid #b0b0b0;

    .chat-list-scrollbar {
      height: calc(100vh - 60px);

      .chat-item {
        display: flex;
        padding: 15px;
        align-items: start;
        justify-content: space-between;

        .l {
          display: flex;
          align-items: center;

          .avatar {
            margin-right: 10px;
          }

          .chat-info {
            height: 45px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .top {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .name {
                font-size: 15px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                margin-bottom: 5px;
              }
            }

            .bottom {
              .content-chat-content {
                color: #8c8c8c;
                font-size: 12px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }

        .time {
          height: 45px;
          display: flex;
          flex-direction: column;
          align-items: end;
          justify-content: space-between;

          .time-text {
            font-size: 12px;
            color: #8c8c8c;
          }

          .icon-qingwudarao {
            font-size: 13px;
          }
        }

        &:hover {
          background-color: #ccc;
        }
      }
    }
  }
}

.right-main {
  .head {
    height: 60px;
    border-bottom: 1px solid #eae7e6;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-left: 20px;
    justify-content: space-between;

    .more {
      width: 20px;
      height: 20px;
      margin: 10px 20px 0 0;
      cursor: pointer;
      color: #8c8c8c;
      padding: 15px 0 0 5px;
      display: flex;
      align-items: center;
      justify-content: center;

      .icon-more {
        font-size: 25px;
      }

      &:hover {
        color: #000;
      }
    }
  }

  .chat-list {
    .chat-list-scrollbar {
      height: calc(100vh - 60px - 150px);
      border-bottom: 1px solid #5f5f5f;
      background: #e8e8e8;
    }

    .chat-input {
      background: #e8e8e8;

      .headA {
        padding: 10px 20px 10px 20px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .headA-a {
          color: #696969;
          font-size: 20px;
          margin-top: 5px;
          cursor: pointer;

          &:hover {
            color: #000;
          }
        }
      }

      .send-button {
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: end;
        padding: 20px 30px 20px 20px;

        .disabled-button {
          width: 100px;
          height: 30px;
          background-color: #c4c3c2;
          border: none;
          color: #ffffff;
          cursor: default;
        }

        .not-disabled-button {
          width: 100px;
          height: 30px;
          background-color: #07bf5f;
          border: none;
          color: #ffffff;

          &:hover {
            background-color: #00af54;
          }
        }
      }
    }
  }

  .Drag-the-mask {
    position: absolute;
    top: 0;
    background-color: rgba(0, 0, 0, 0.6);
  }
}

:deep(.el-badge__content) {
  font-size: 10px;
  border: none;
}

.active {
  background-color: #dcdcdcff;
}

.blank-page-top {
  height: 60px;
}

.blank-page {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 100px;
  color: #ddd;
  height: calc(100vh - 62px);
}

#message-input {
  color: #000;
  font-size: 14px;
  height: 50px;
  padding: 0 11px 0 20px;
  overflow: auto;
  border: none;
  outline: none; /* 关闭轮廓 */
  box-sizing: border-box; /* 边框和内边距包含在宽度内 */

  white-space: pre-wrap; /* 保留换行符 */
  word-wrap: break-word; /* 在单词中间断开 */
  overflow-wrap: break-word; /* 在单词中间断开 */
  max-width: 100%; /* 确保宽度不超过容器 */
  caret-color: #00af54;
}

.annex {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
  position: absolute;
  top: 0;
  z-index: 100;
  left: 0;

  .annex-card {
    width: 300px;
    height: 400px;
    padding-top: 10px;

    .title {
      padding-bottom: 10px;
      width: 300px;
      display: flex;
      align-items: center;
      justify-content: center;
      //border-bottom: 1px solid #eae7e6;
      margin-bottom: 5px;
    }

    .annex-item {
      padding: 10px 20px 10px 20px;
      border-bottom: 1px solid #eae7e6;

      .annex-item-content {
        display: flex;
        align-items: center;
        user-select: none;

        .file-icon {
          margin-right: 10px;
        }

        .file-info {
          margin-right: 10px;

          .file-name {
            font-size: 15px;
          }
        }
      }

      .file-delete {
        visibility: hidden;
        cursor: pointer;
      }

      &:hover {
        .file-delete {
          visibility: visible;
        }
      }
    }

    .annex-bottom {
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;

      .el-button {
        margin: 5px;
        height: 25px;
        width: 100px;
      }
    }
  }
}

.drawer {
  height: calc(100vh - 60px);
  background-color: #fff;
}

:deep(.el-overlay) {
  margin-top: 60px;
}

.menu-card {
  position: absolute;
  z-index: 10;

  .card {
    border-radius: 0;
    width: 120px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .card-text {
      width: 120px;
      user-select: none;
      font-size: 16px;
      height: 25px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border-bottom: 0.5px solid #eaeaea;

      &.delete-contact {
        &:hover {
          background: #ff5151;
        }
      }

      &:hover {
        background: #eaeaea;
      }
    }
  }
}

.card-contact {
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  .card-contact-info {
    width: 250px;
    height: 150px;

    .button {
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-badge__content.is-fixed) {
  z-index: 0;
}

.message-wrapper {
  display: flex;
  width: 100%;
  margin: 10px 0;
  padding: 0 10px;

  &.mine-wrapper {
    justify-content: flex-end;
  }

  &.other-wrapper {
    justify-content: flex-start;
  }
}

.time-module {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #7a7a7a;
  font-size: 12px;
}

.message-group {
  display: flex;
  align-items: flex-start;
  max-width: 500px;

  &.other-group {
    .message-avatar {
      margin-right: 10px;
      flex-shrink: 0;
    }
  }

  &.mine-group {
    display: flex;
    align-items: flex-end;

    .message-warning {
      margin-bottom: 35px;
      width: 20px;
      height: 20px;
      margin-right: 10px;
      background-color: #ff0000;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      color: #ffffff;
      padding: 5px;
      font-size: 15px;
      cursor: pointer;
    }

    .message-avatar {
      margin-left: 10px;
      flex-shrink: 0;
    }
  }
}

.message-avatar {
  align-self: flex-start;
}

.bubble {
  max-width: 500px;
  padding: 10px;
  border-radius: 10px;
  position: relative;
  word-break: break-all;

  &.other {
    background-color: #ffffff;
    color: #000;

    &::after {
      content: '';
      position: absolute;
      top: 10px;
      left: -10px;
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 6px 10px 6px 0;
      border-color: transparent transparent transparent #ffffff;
    }
  }

  &.mine {
    background-color: #94ea68ff;
    color: #000;

    &::after {
      content: '';
      position: absolute;
      top: 10px;
      right: -10px;
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 6px 0 6px 10px;
      border-color: transparent transparent transparent #94ea68ff;
    }
  }
}

.media-content {
  max-width: 300px;
  display: block;
}

//#slider {
//  position: absolute;
//  top: 60px; /* 距离顶部的距离 */
//  left: 0;
//  width: 200px;
//  height: 100px;
//  background-color: #f9f9f9;
//  transform: translateX(-100%); /* 初始位置在左侧完全隐藏 */
//  transition: transform 0.3s ease-in-out; /* 平滑过渡效果 */
//}
//
//#slider.active {
//  transform: translateX(0); /* 滑动到可见位置 */
//}
</style>
